#!/usr/bin/env python3
"""
直接测试Qwen3-VL API
"""
import requests
import json
import time

def test_qwen_api():
    """直接测试Qwen3-VL API"""
    
    # API配置
    api_url = "http://192.168.200.19:18009/api/generate"
    video_url = "http://192.168.210.72:8000/videos/502be57a-11fa-465a-8708-b993125d399e.mp4"
    
    # 请求数据
    request_data = {
        "prompt": "请详细描述这个视频的内容，包括场景、人物、动作和主要事件",
        "model": "Qwen3-VL",
        "videos": [video_url],
        "stream": False
    }
    
    # 请求头
    headers = {
        "Content-Type": "application/json",
        "Accept": "*/*",
        "Connection": "keep-alive"
    }
    
    print("🚀 开始测试Qwen3-VL API...")
    print(f"📍 API地址: {api_url}")
    print(f"🎬 视频URL: {video_url}")
    print(f"💬 提示词: {request_data['prompt']}")
    print()
    
    try:
        # 1. 先测试视频URL是否可访问
        print("1️⃣ 测试视频URL可访问性...")
        video_response = requests.head(video_url, timeout=10)
        print(f"   视频URL状态: {video_response.status_code}")
        if video_response.status_code == 200:
            print(f"   视频大小: {video_response.headers.get('content-length', '未知')} bytes")
            print(f"   内容类型: {video_response.headers.get('content-type', '未知')}")
        print()
        
        # 2. 测试Qwen3-VL API连接
        print("2️⃣ 测试Qwen3-VL API连接...")
        try:
            # 尝试访问可能的健康检查端点
            health_url = api_url.replace('/api/generate', '/health')
            health_response = requests.get(health_url, timeout=5)
            print(f"   健康检查状态: {health_response.status_code}")
        except Exception as e:
            print(f"   健康检查失败: {e}")
        print()
        
        # 3. 发送实际请求
        print("3️⃣ 发送Qwen3-VL分析请求...")
        print(f"   请求数据: {json.dumps(request_data, ensure_ascii=False, indent=2)}")
        print()
        
        start_time = time.time()
        response = requests.post(
            api_url,
            json=request_data,
            headers=headers,
            timeout=300  # 5分钟超时
        )
        end_time = time.time()
        
        print(f"⏱️ 请求耗时: {end_time - start_time:.2f}秒")
        print(f"📊 响应状态: {response.status_code}")
        print(f"📋 响应头: {dict(response.headers)}")
        print()
        
        if response.status_code == 200:
            print("✅ 请求成功！")
            try:
                result = response.json()
                print("📄 响应内容 (JSON):")
                print(json.dumps(result, ensure_ascii=False, indent=2))
            except json.JSONDecodeError:
                print("📄 响应内容 (文本):")
                print(response.text)
        else:
            print("❌ 请求失败！")
            print(f"错误内容: {response.text}")
            
    except requests.exceptions.Timeout:
        print("❌ 请求超时")
    except requests.exceptions.ConnectionError as e:
        print(f"❌ 连接错误: {e}")
    except Exception as e:
        print(f"❌ 其他错误: {e}")

def test_video_accessibility():
    """测试视频文件可访问性"""
    video_url = "http://192.168.210.72:8000/videos/502be57a-11fa-465a-8708-b993125d399e.mp4"
    
    print("🔍 测试视频文件可访问性...")
    print(f"📍 视频URL: {video_url}")
    
    try:
        # HEAD请求测试
        response = requests.head(video_url, timeout=10)
        print(f"✅ HEAD请求成功: {response.status_code}")
        print(f"   Content-Type: {response.headers.get('content-type')}")
        print(f"   Content-Length: {response.headers.get('content-length')}")
        
        # 部分GET请求测试
        response = requests.get(video_url, headers={'Range': 'bytes=0-1023'}, timeout=10)
        print(f"✅ 部分GET请求成功: {response.status_code}")
        print(f"   获取数据长度: {len(response.content)} bytes")
        
    except Exception as e:
        print(f"❌ 视频访问失败: {e}")

if __name__ == "__main__":
    print("=" * 60)
    print("Qwen3-VL API 直接测试工具")
    print("=" * 60)
    print()
    
    # 测试视频可访问性
    test_video_accessibility()
    print()
    print("-" * 60)
    print()
    
    # 测试API
    test_qwen_api()
    
    print()
    print("=" * 60)
    print("测试完成")
    print("=" * 60)